package com.tcs.netty.main;

import com.tcs.netty.channel.ChannelInit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class NettyMain {

    private static final Logger logger = LoggerFactory.getLogger(NettyMain.class);

    private String nettyPort;

    public void start() {
        new Thread("netty-thread") {
            @Override
            public void run() {
                NioEventLoopGroup group = new NioEventLoopGroup();
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                try {
                    logger.info("参数配置的 PROT : {}  " , nettyPort);
                    serverBootstrap.group(group)
                            .channel(NioServerSocketChannel.class)
                            //保持连接数
                            .option(ChannelOption.SO_BACKLOG, 128)
                            //有数据立即发送
                            .option(ChannelOption.TCP_NODELAY, true)
                            //保持连接
                            .childOption(ChannelOption.SO_KEEPALIVE, true)
                            .localAddress(new InetSocketAddress(NumberUtils.toInt(nettyPort)))
                            .childHandler(new ChannelInit());
                    ChannelFuture channelFuture = serverBootstrap.bind().sync();
                    channelFuture.channel().closeFuture().sync();
                } catch (Exception e) {
                    logger.error("", e);
                } finally {
                    try {
                        group.shutdownGracefully().sync();
                    } catch (InterruptedException e) {
                        logger.error("", e);
                    }
                }
            }
        }.start();
    }

    public void setNettyPort(String nettyPort) {
        this.nettyPort = nettyPort;
    }

    public String getNettyPort() {
        return nettyPort;
    }
}
